/**
 * 按需维保
 */
import {Component, NgModule, OnInit, Input, Output, EventEmitter} from "@angular/core";

import {Router} from "@angular/router";
import {NzModalService, NzModalSubject, NzNotificationService, UploadFile} from "ng-zorro-antd";
import * as moment from "moment";
import {HttpServcie} from "../../../../service/http.service";
import {Config} from "../../../../service/config";
import {DemandMaintenanceBean} from "../../bean/demandMaintenance.bean";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ContractBean} from "../../../contract/bean/contract.bean";
import {ElevatorInfoBean} from "../../../elevator/elevator-info/bean/elevatorInfo.bean";



@Component({
  selector: "demandMaintenance-update",
  templateUrl: "demandMaintenance-update.html",
  styleUrls: ["demandMaintenance-update.scss"]
})

export class DemandMaintenanceUpdate {
  constructor(
    private httpService: HttpServcie,
    private router: Router,
    private _notification: NzNotificationService,
    private nsub: NzModalSubject,
    private modalService: NzModalService,
    private fb: FormBuilder
  ) {
    this.user = JSON.parse(window.localStorage.getItem("user"));
  }
  @Input() inValue: any = [];
  @Output() outValue = new EventEmitter();
  validateForm: FormGroup;

  // //业务参数
  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();
  demandMaintenance : DemandMaintenanceBean = new DemandMaintenanceBean();
  user : any;
  weibaoList : any; //获取与当前使用单位有合同关系的维保单位
  createList : any = []; //获取当前使用单位电梯台账所有的制造单位
  insuranceList  = []; //保险公司信息
  createCompanyName : any = []; //制造单位
  maintenanceCycleList : any = [];//维保周期
  //获取电梯参数
  elevatorList : any;
  total = 0;
  outsidenumStr : string = ""; //选中电梯的外部编码

  //多选框
  allChecked: any = false;
  indeterminate: any = false;
  elevatorIds : any = [];
  elevatorTypes = [
    {'label' : '载客电梯', 'value' : '1'},
    {'label' : '载货电梯', 'value' : '5'},
    {'label' : '自动扶梯', 'value' : '4'},
    {'label' : '自动人行道', 'value' : '6'}];  //按需维保申请状态

  //模态框参数
  modelTitle : string = "";
  modal: any = 0;
  currentModal: NzModalSubject;
  updateData: any = {};

  ngOnInit(){
    this.validateForm = this.fb.group({
      userPartyId : [null, [Validators.required]], //使用单位
      maintenancePartyId: [null, [Validators.required]], //维保单位
      createCompanyName : [null, [Validators.required]], //制造单位
      maintenanceCycle: [null, [Validators.required]], //维保周期
      startDate: [null, [Validators.required]], //开始时间
      endDate: [null, [Validators.required]], //结束时间
      haveTestSystem : [null, [Validators.required]],
      haveInsurance : [null, [Validators.required]],
      outsidenumStr : [null, []],
      insuranceName : [null, []], //保险公司
      insuranceDate : [null, []], //保险到期时间
      insuranceName1: [null, []],
      insuranceName2: [null, []],
      insuranceName3: [null, []],
      insuranceName4: [null, []],
      insuranceDate1: [null, []],
      insuranceDate2: [null, []],
      insuranceDate3: [null, []],
      insuranceDate4: [null, []],
    });
    if (this.inValue) {
      this.demandMaintenance = Object.assign({}, this.inValue);
    }
    this.elevatorIds = this.demandMaintenance.elevatorIds.split(",");

    //获取与使用单位有合同关系的维保单位
    let contractBean = new ContractBean();
    contractBean.partyId  = this.demandMaintenance.userPartyId;
    contractBean.partyType = this.user.partyType;
    this.httpService.contractQueryByPartyIdList(contractBean).subscribe(data => {
      if (data.status === 200) {
        this.weibaoList = data.data.list;
      } else if (data.status === 401) {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }
    });

    //获取与使用单位有关系的制造单位
    let  elevatorInfo :　ElevatorInfoBean = new ElevatorInfoBean();
    elevatorInfo.usedPartyId = this.user.partyId;
    this.httpService.elevatorCreateCompany(elevatorInfo).subscribe(data => {
      if (data.status === 200) {
        let tempList = data.data.list;
        tempList.forEach(ele =>{
          this.createList.push({"value":ele});
        });

      } else if (data.status === 401) {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }
    });

    //获取保险公司
    let insuranceNameList = this.demandMaintenance.insuranceName.split("|");
    let insuranceDateList = this.demandMaintenance.insuranceDate.split("|");
    let len = insuranceNameList.length;
    for(let i = 0;i<len;i++){
      this.insuranceList.push({name: insuranceNameList[i], date: insuranceDateList[i]})
    }

    let elevatorInfo1 :　ElevatorInfoBean = new ElevatorInfoBean();
    let tempList : any;
    elevatorInfo1.elevatorIds = this.elevatorIds;
    this.httpService.demandMaintGetElevators(elevatorInfo1).subscribe(data =>{
      if(data.status == 200){
        tempList = data.data.list;
        tempList.forEach(ele=>{
          this.outsidenumStr = this.outsidenumStr + ele.outsideNum  + ",";
        });
      }else{
        this._notification.create('error', '错误提示', '查询失败');
      }
    });
  }

  submitForm(){
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
    }

    for (const i in this.validateForm.controls) {
      if (!this.validateForm.controls[i].valid) {
        return;
      }
    }

    let nameList = [];
    let dateList = [];
    this.insuranceList.forEach(item => {
      if (item.name) {
        nameList.push(item.name);
      }
      if (item.date) {
        dateList.push(moment(item.date).format("YYYY-MM-DD"));
      }
    });

    if(nameList.length == 0){
      this._notification.create("error", "错误提示", "请填写保险公司！");
      return;
    }

    if(this.elevatorIds.length == 0){
      this._notification.create("error", "错误提示", "请添加电梯！");
      return;
    }
    this.demandMaintenance.insuranceName = nameList.join('|');
    this.demandMaintenance.insuranceDate = dateList.join('|');

    //取得选择的电梯
    this.demandMaintenance.elevatorIds = this.elevatorIds.join(",");
    /**
     * 获取当前使用单位的上级监管单位与上上级监管单位
     */

    this.demandMaintenance.startDate = moment(this.demandMaintenance.startDate).format("YYYYMMDD");
    this.demandMaintenance.endDate = moment(this.demandMaintenance.endDate).format("YYYYMMDD");
    this.httpService.updateDemandMaintence(this.demandMaintenance).subscribe(data => {
      if (data["status"] == "200") {
        this._notification.create("success", "提示", "修改成功！");
      }else{
        this._notification.create("error", "错误提示", "修改失败！");
        return;
      }
      this.outValue.emit(true);
    });
  }

  quit() {
    this.outValue.emit(true);
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  addInsurance() {
    this.insuranceList.push({name: '', date: ''})
  }

  deleteInsurance(item) {
    let i = this.insuranceList.indexOf(item);
    this.insuranceList.splice(i, 1);
  }

  changeMintenceCycle(){
    if(this.demandMaintenance.haveTestSystem == '0') {
      this.maintenanceCycleList = [
        {'label': '一个月', 'value': '一个月'},
        {'label': '二个月', 'value': '二个月'},
        {'label': '三个月', 'value': '三个月'}
      ];
    }else{
      if(this.demandMaintenance.haveInsurance == '0'){
        this.maintenanceCycleList = [
          {'label': '一个月', 'value': '一个月'},
          {'label': '二个月', 'value': '二个月'}
        ];
      }else{
        this.maintenanceCycleList = [
          {'label': '一个月', 'value': '一个月'}
        ];
      }
    }
  }

  addElevator(title, content, footer){
    if (JSON.parse(window.localStorage.getItem("user")).partyType != 2) {
      this._notification.create("error", "错误提示", "您无权限");
      return;
    }
    this.elevatorInfo.pageSize = 10;
    this.elevatorInfo.currentPage = 1;
    this.modelTitle = "添加电梯";
    this.modal = 0;
    if(!this.demandMaintenance.userPartyId || !this.demandMaintenance.maintenancePartyId || ! this.demandMaintenance.createCompanyName){
      this._notification.create("error", "错误提示", "请先填写单位相关信息！");
      return;
    }
    this.queryElevator();
    this.currentModal = this.modalService.open({
      title: title,
      content: content,
      footer: footer,
      maskClosable: false,
      width: 1000,
      zIndex: 2000,
      style: {
        top: "20px"
      },
      onOk() {
        console.log("Click ok");
      }
    });
  }

  /**
   * 获取电梯
   */
  queryElevator(){
    this.elevatorInfo.usedPartyId = this.demandMaintenance.userPartyId;
    this.elevatorInfo.maintenancePartyId = this.demandMaintenance.maintenancePartyId;
    this.elevatorInfo.createCompanyName = this.demandMaintenance.createCompanyName;
    this.elevatorInfo.elevatorTypeIds = ['1','4','5','6'];
    this.httpService.demandMaintGetElevators(this.elevatorInfo).subscribe(
      data => {
        if (data.status == 200) {
          this.elevatorList = data.data.list;
          this.total = data.data.total;
          //再次点击，回显已选择
          this.elevatorList.forEach(element1 => {
            this.elevatorIds.forEach(element2 => {
              if (element1.id == element2) {
                element1.checked = true;
              }
            });
          });
        } else if (data.status === 401) {
          this.router.navigateByUrl("/login");
          return;
        } else {
          // 异常
          this._notification.create("error", "错误提示", data.message);
        }
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  /**
   * 保存勾选的电梯
   */
  saveElevators(){

    //再次点击时重新给值
    const tempList: any = [];
    this.elevatorList.forEach(element => {
      let isNotExist = true;
      if (element.checked) {
        if(element.isInsure == '否'){
          this._notification.create("error", "错误提示", "请选择参与保险的电梯！");
          return;
        }
        tempList.push(element);
        this.elevatorIds.forEach(element1 =>{
          if(element.id == element1){
            isNotExist = false;
          }
        });
        if(isNotExist){
          this.outsidenumStr = this.outsidenumStr + element.outsideNum + ",";
          this.elevatorIds.push(element.id + "");
        }
      }
    });
    if (tempList.length == 0) {
      // 异常
      this._notification.create("error", "错误提示", "至少选中一条数据！");
      return;
    }

    this.currentModal.destroy();
  }

  clear(){
    this.outsidenumStr = "";
    this.elevatorIds.splice(0,this.elevatorIds.length);
  }

  //添加返回
  addCall(event) {
    this.currentModal.destroy();
  }


  //table加载数据时
  displayDataChange($event) {
    this.elevatorList = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.elevatorList.every(
      value => value.disabled || value.checked
    );
    const allUnChecked = this.elevatorList.every(
      value => value.disabled || !value.checked
    );
    this.allChecked = allChecked;
    this.indeterminate = !allChecked && !allUnChecked;
  }

  //全选
  checkAll(value) {
    if (value) {
      this.elevatorList.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.elevatorList.forEach(data => (data.checked = false));
    }
  }

  //分页
  nzPageSizeChange(event) {
    this.elevatorInfo.pageSize = event;
    this.elevatorInfo.currentPage = 1;
    this.queryElevator();
  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.elevatorInfo.currentPage = event;
    this.queryElevator();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.elevatorInfo.currentPage = event;
    this.queryElevator();
  }
  // 查询面板
  panels = {
    active: true,
    name: "查询",
    disabled: false,
    childPanel: [
      {
        active: false,
        name: "查询"
      }
    ]
  };

}
